﻿using System;
using System.Data;
using Ntt.NttData.Been.CommonLibrary.Database.SqlServer;

namespace NTTDATA.BEENChina.CaseMonitor.CaseChecker
{
    [Serializable]
    public class Management : Note
    {
        public String Sql
        {
            get { return ConstructSql(); }
        }

        private String GetDBconnString()
        {
           
            return String.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3}", this.Address, DBName, UserId, PassWord);
        }

        protected override int calcCount()
        {
            int count = 0;
            try
            {
           
                int.TryParse(new SqlHelper().ExecuteScalar(GetDBconnString(), CommandType.Text, Sql).ToString(), out count);

                Log.Console.Debug(string.Format("Ma Address:{0}{3}  Count:{1}{3}  Sql:{2}", Address, count, Sql, Environment.NewLine));
            }
            catch (Exception ex)
            {
                Log.Console.Error(string.Format("Ma Address:{0}{3}  Count:{1}{3}  Sql:{2}", Address, count, Sql, Environment.NewLine));
                Log.Console.Error("CaseChecker Management error", ex);
            }

            return count;
        }

        /// <summary>
        /// {0}: 需要调整的时间 分钟，整型
        ///      正数 往后调整;负数 往前调整
        /// {1}: 调整后的开始时刻 ex: 01:00:00 
        /// {2}: 调整后的开始时刻 ex: 05:00:00 
        /// </summary>
        /// <returns>sql</returns>
        private String ConstructSql()
        {
            String sql = "SELECT COUNT(*)  FROM [OrderQueue] WITH(NOLOCK) " +
                   "WHERE CustomerID = '{3}' AND "+
                   " DATEADD( mi, {0},[ReceiveTime])  BETWEEN '{4} {1}' AND '{4} {2}'";
                   //"RIGHT( CONVERT(NVARCHAR(19), DATEADD( mi, {0},[ReceiveTime]),120),8) BETWEEN '{1}' AND '{2}'";

            String tuneMi = String.IsNullOrEmpty(base.TuneMi.Trim()) ? "0" : base.TuneMi;

            String now = System.DateTime.Now.ToString("HH:mm");

            sql = String.Format(sql, tuneMi, DateFrom, String.IsNullOrEmpty(DateTo) ? now : DateTo, CustomerID, System.DateTime.Now.ToString("yyyy-MM-dd"));

            return sql;
        }

    }
}